package design_mode.singleton;

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class singleton_1Test {

    @Test
    void testInstance() {
        Singleton instance1 = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        assertSame(instance1, instance2, "");
    }

    @Test
    void testSingletonIsThreadSafe() throws InterruptedException {
        final int n = 100;
        Thread[] threads = new Thread[n];
        final singleton_1[] instances = new singleton_1[n];

        // 创建多个线程来并发获取单例实例
        for (int i = 0; i < n; i++) {
            threads[i] = new Thread(() -> {
                instances[(int) (Thread.currentThread().getId() % n)] = singleton_1.getInstance();
            });
            threads[i].start();
        }
        // 等待所有线程完成
        for (Thread thread : threads) {
            thread.join();
        }
        // 验证所有线程获取到的实例是否相同
        for (int i = 1; i < n; i++) {
            assertSame(instances[0], instances[i], "All instances should be the same");
        }
    }
}